package mil.af.amc.adpetracker.web.actions.struts1.EquipmentItem;

import mil.af.amc.adpetracker.model.EquipmentItem;
import mil.af.amc.adpetracker.model.Manufacturer;
import mil.af.amc.adpetracker.service.EquipmentItemService;
import mil.af.amc.adpetracker.web.actions.struts1.AbstractAction;
import net.sf.json.JSONObject;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * Please Fill in this Javadoc
 *
 * @author TSgt Jason Ferguson
 */

public class GetItemBySerialAction extends AbstractAction {

    private EquipmentItemService equipmentItemService;

    public void setEquipmentItemService(EquipmentItemService equipmentItemService) {
        this.equipmentItemService = equipmentItemService;
    }

    @Override
    public ActionForward execute(ActionMapping actionMapping,
                                 ActionForm actionForm,
                                 HttpServletRequest httpServletRequest,
                                 HttpServletResponse httpServletResponse) throws Exception {

        String serial = httpServletRequest.getParameter("search").toUpperCase();

        // Normally I try not to instantiate actual objects in the Controller, but ajax stuff is an exception
        EquipmentItem item = equipmentItemService.getBySerialNumber(serial);

        // Short circuit here to prevent unnecessary stuff, NPE's, etc
        if (item==null) {
            return null;
        }

        Map itemMap = item.toMap();

        // The table needs the manufacturer name...
        Manufacturer manu = item.getItemModel().getManufacturer();
        itemMap.put("manufacturerName", manu.getName());

        JSONObject jsonObject = JSONObject.fromObject(itemMap);

        httpServletResponse.setContentType("application/json");
        httpServletResponse.getWriter().println(jsonObject);

        return null;
    }
}
